package com.yc.chatroom.client;

import com.google.common.base.Strings;
import com.yc.chatroom.common.Constant;
import com.yc.chatroom.common.dto.LoginDto;
import com.yc.chatroom.common.dto.LoginResponse;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginService {
	Log log = LogFactory.get();
	
	@Autowired
	private ClientManager clientManager;

	public LoginResponse login(String userName, String password) {
		LoginResponse res = new LoginResponse();
		//校验数据
		if (Strings.isNullOrEmpty(userName) || Strings.isNullOrEmpty(password)) {
			res.setCode(Constant.RESULT_CODE_ILLEGAL_PARAM);
			res.setMsg("账号或密码为空");
			return res;
		}
		//清掉登录返回值（强行改掉该值是没有意义的，因为之后的每个请求都会校验连接）
		clientManager.loginResponse = null;
		//封装对象
		LoginDto loginDto = new LoginDto(userName, password, Constant.FUNCTION_CODE_CHATROOM);
		//发送数据
		clientManager.sendMsg(loginDto);

		//轮询等待服务器的响应:轮询10次，每次最多等待200毫秒，总共最多等待两秒
		for (int i = 0; i < 10; i++) {
			try {
				log.info("登录中...");
				if (null != clientManager.loginResponse) {
					log.info("登录成功");
					return clientManager.loginResponse;
				}
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		
		res.setCode(Constant.RESULT_CODE_PROGRAM_ERROR);
		res.setMsg("登录超时");
		return res;
		
	}
}
